package com.yihu.cms.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.yihu.article.beans.LoginResult;
import com.yihu.article.beans.UserQuery;
import com.yihu.beans.ResultVO;
import com.yihu.beans.dic.DatadicQuery;
import com.yihu.beans.dic.Resource;
import com.yihu.beans.user.UserPriviledge;
import com.yihu.cms.service.DataDictionaryService;
import com.yihu.cms.service.UserService;
import com.yihu.cms.service.WexinMsgByGroupService;
import com.yihu.cms.util.CMSConstants;
import com.yihu.cms.util.CommonUtils;
import com.yihu.cms.util.InfoHelp;
import com.yihu.cms.util.Osslog;
import com.yihu.web.bean.SignUp;
import com.yihu.web.bean.vo.UsersQuery;
import com.yihu.web.constats.DSConstants;
import com.yihu.beans.user.User;
/**
 * 
 * @author Aaron
 *
 */
@Controller
public class UserController extends BaseController{
	private final Logger logger = LoggerFactory.getLogger(UserController.class); 
	@Autowired
	private HttpServletRequest request;
	UserService as = new UserService();
	
	@RequestMapping(value = "/user/login", method = RequestMethod.POST)
	public @ResponseBody Object login(@RequestBody User user) {
		String result = as.login(JSON.toJSONString(user));
		LoginResult lr = JSON.parseObject(result, LoginResult.class);
		if(lr.getResult() == CMSConstants.R_SUCCESS){
			Cookie cookie = new Cookie("userId",String.valueOf(lr.getUserId()));
			//cookie.setMaxAge(3600);
			response.addCookie(cookie);
		}
		return lr;
	}
	
	
	@RequestMapping(value = "/user/logout/{userId}", method = RequestMethod.GET)
	public @ResponseBody Object logout(@PathVariable("userId") long userId) {
		Cookie[] cookies = request.getCookies();
		for(Cookie cookie : cookies){
		    if(cookie.getValue().equals(userId)){
		    	cookie.setMaxAge(0);
		    }
		}
		ResultVO rv = as.logout(userId);
		return JSON.toJSONString(rv);
	}
	
	@RequestMapping(value = "/user/isValid/{userId}", method = RequestMethod.GET)
	public @ResponseBody Object isValid(@PathVariable("userId") long userId) {
		System.out.println("into isValid: "+userId);
		String userJson = as.isValidOfUser(userId);
		if(!InfoHelp.isBlank(userJson)){
			/*LoginResult lr = JSON.parseObject(userJson, LoginResult.class);
			logger.debug("userName: "+lr.getUserName());
			return JSON.parseObject(userJson, LoginResult.class);*/
			return CommonUtils.getResult(0, null);
		}
		else{
			return CommonUtils.getResult(1, 401);
		}
		
		
	}
	
	
	@RequestMapping(value = "/user/changePassword", method = RequestMethod.POST)
	public @ResponseBody Object changePassword(@RequestBody User user) {
		ResultVO rv = as.changePassword(JSON.toJSONString(user));
		return JSON.toJSONString(rv);
	}
	
	
	@RequestMapping(value = "/user", method = RequestMethod.POST)
	public @ResponseBody Object addUser(@RequestBody User user) {
		user.setModel(0); //cms user
		ResultVO rv = as.add(JSON.toJSONString(user));		
		return JSON.toJSONString(rv);
	}
	
	@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT)
	public @ResponseBody Object updateUser(@RequestBody User user,@PathVariable("id") long id) {
		user.setUserId(id);
		String json = JSON.toJSONString(user);
		Osslog.debug("json: "+json);
		ResultVO rv = as.update(json);
		Osslog.debug("ResultVO: "+JSON.toJSONString(rv));
		return JSON.toJSONString(rv);
	}
	
	@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
	public @ResponseBody Object deleteUser(@PathVariable("id") long id) {
		ResultVO rv = as.delete(id);
		return JSON.toJSONString(rv);
	}
	
	@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
	public @ResponseBody Object getUser(@PathVariable("id") long id) {
		System.out.println("id: "+id);
		String userJson = as.getUserById(id);
		return JSON.parseObject(userJson, User.class);
	}
		
	@RequestMapping(value = "/user/list" , method = RequestMethod.GET)
	// , method = RequestMethod.PATCH
	public @ResponseBody Object getUsersPaging(UserQuery query) {
		
		UserService as = new UserService();
		String json = JSON.toJSONString(query);
		String resultJson= as.getUsersPaing(json);
		return JSON.parse(resultJson);
	}
	/***
	 * 设置用户代理商级别
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/setAgentLevel", method = RequestMethod.PUT)
	public @ResponseBody Object setAgentLevel(@RequestBody User user) {
		System.out.println("into setAgentLevel: "+user);
		return as.setAgentLevel(user);
	} 
	
	/***
	 * 设置普通用户级别
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/user/setUserLevel", method = RequestMethod.PUT)
	public @ResponseBody Object setUserLevel(@RequestBody User user) {
		System.out.println("into setUserLevel: "+user);
		return as.setUserLevel(user);
	} 
	
	
	@RequestMapping(value = "/user/getPriviledge", method = RequestMethod.GET)
	public @ResponseBody Object getUserPriviledge(@RequestParam("userId") long userId) {
		Object o = as.getPriviledgesByUserId(userId);
		if(o instanceof ResultVO){
			return Collections.emptyList();
		}
		return JSON.parse(JSON.toJSONString(o));
	}
	
	@RequestMapping(value = "/user/group1", method = RequestMethod.GET)
	public @ResponseBody Object group1() {
		return WexinMsgByGroupService.getCustomerService();
	}
	
	@RequestMapping(value = "/user/group2", method = RequestMethod.GET)
	public @ResponseBody Object group2() {
		return WexinMsgByGroupService.getConsultService();
	}
	
	public static void main(String[] args) {
		List<UserPriviledge> ps = new ArrayList<>();
		UserPriviledge u1 = new UserPriviledge();
		u1.setGroupName("11");
		u1.setPermitName("p1");
		
		UserPriviledge u2 = new UserPriviledge();
		u2.setGroupName("12");
		u2.setPermitName("p2");
		ps.add(u1);
		ps.add(u2);
		String json = JSON.toJSONString(ps);
		System.out.println(json);
		ps = JSON.parseArray(json, UserPriviledge.class);
		
		for(UserPriviledge u:ps){
			System.out.println(u.getGroupName());
		}
	}
	
	@RequestMapping(value = "/user/sendDeliveryMesBySms", method = RequestMethod.GET)
	public @ResponseBody Object userSendDeliveryMesBySms(String userName,
			String mobileNumber, String expressName, String courierNumber) {
		logger.debug("userSendDeliveryMesBySms: userName=" + userName
				+ ",mobileNumber=" + mobileNumber + ",expressName="
				+ expressName + ",courierNumber=" + courierNumber);
		com.yihu.web.bean.user.User user = new com.yihu.web.bean.user.User();
		user.setUserName(userName);
		user.setMobileNumber(mobileNumber);
		
		SignUp signup = new SignUp();
		signup.setType(3);
		signup.setUser(user);
		/*signup.setExpressName(expressName);
		signup.setCourierNumber(courierNumber);*/
		
		return as.sendDeliveryMesBySms(signup);
	}
	
	/***
	 * 获取用户砍价次数，根据类型，等级从数据字典获取。
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/user/cuttimes", method = RequestMethod.GET)
	public @ResponseBody Object getUserInfoForCut(UsersQuery u) {
		String userJson = as.getUserById(u.getUserId());
		User user = JSON.parseObject(userJson, User.class);
		Osslog.info("cuttimes.user: "+user);
		//通过parentPath and keyName 获取对象值
		DataDictionaryService service = new DataDictionaryService();
		DatadicQuery query = new DatadicQuery();
		int model = user.getModel();
		String level = user.getLevel();
		if(StringUtils.isBlank(level)){
			level = "lv0";
		}
		StringBuffer sb = new StringBuffer();
		sb.append("/cms/config/userlevel/"+level);
		if(model==DSConstants.USER_MODEL_NORMAL||model==DSConstants.USER_MODEL_SYSTEM){
			sb.append("/generaluser");
		}
		else {
			sb.append("/agentuser");
		}
		query.setParentPath(sb.toString());
		if(u.getType().equals("add")){
			query.setKeyName("add");
		}else{
			query.setKeyName("assist");
		}
		Resource r = service.getDicByPath(query);
		Osslog.info("cuttimes.Resource: "+r);
		Map<String,Object> map = new HashMap<String,Object>();
		if(r!=null)
			map.put("times", r.getValue());
		else{
			map.put("times", 50);
		}
		return map;
	}
	
}
